<?php

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper as FHelper;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\GraphObject;
class UsersController extends ControllerBase
{
	public static function upload($user_id,$from,$height,$width)
	{
		return \Cloudinary\Uploader::upload($from,
	    array(
	       "public_id" => $user_id,
	       "height" => $height,
	       "width" => $width,
	       "invalidate" => true
	    ))['version'];

	}

	public function presenceAction()
	{
		
		$socket_id = $_POST['socket_id'];
		$channel_name = $_POST['channel_name'];		 

		$pusher = new Pusher(
		    PUSHER_APP_KEY, //APP KEY
		    PUSHER_APP_SECRET, //APP SECRET
		    PUSHER_APP_ID //APP ID
		);
		 
	 	$info = UserAccountTb::findFirst(array(
	        "conditions"=>"id = ?0",
	        "bind"=>array(0=>$this->session->get('user_id')),
	        "columns"=>"id,CONCAT(fname,' ',lname) as fullname,profile_pic"
        ));

	 	
 		if(strlen($info->fullname) > 12){
 		$info->fullname = @substr_replace($info->fullname, '...',11);
 		}
		
		$presence_data = array(
		    'data'=>$info
		);
		 
		echo $pusher->presence_auth(
		    $channel_name, //the name of the channel the user is subscribing to 
		    $socket_id, //the socket id received from the Pusher client library
		   $this->session->get('user_id'),  //a UNIQUE USER ID which identifies the user
		    $presence_data //the data about the person
		);
		die;
		exit();

	}
	public function logoutAction()
	{
		
		$this->session->destroy();
		
		die("Loging Out..");
	}

	public function uploadAction()
	{
		
		
		$this->session->destroy();

		\Cloudinary\Uploader::destroy('profile_pic_1', array("invalidate" => TRUE));
		die;
		/*echo copy(IMAGE_URL_SMALL."sample.jpg", 'C:\Users\Morris_Gaming\Downloads\try.jpg');
		
		// sample uploading
		\Cloudinary\Uploader::upload('C:\Users\Morris_Gaming\Downloads\loading.gif',
	    array(
	       "public_id" => "morakgaming",
	       "crop" => "limit", "width" => "2000", "height" => "2000",
	       "eager" => array(
	         array( "width" => 200, "height" => 200, 
	                "crop" => "thumb", "gravity" => "face",
	                "radius" => 20, "effect" => "sepia" ),
	         array( "width" => 100, "height" => 150, 
	                "crop" => "fit", "format" => "png" )
	       ),                                     
	       "tags" => array( "special", "for_homepage" )
	    ));


		// sample viewing
	    echo cl_image_tag("morakgaming.jpg", array( "alt" => "Sample Image" )); 

	    echo "<img src= ".IMAGE_URL_SMALL."sample.jpg"." width='100' height='150' />";  */
		$this->view->disable();

	}


    public function fbloginAction()
    {
    	$this->session->start();
    	FacebookSession::setDefaultApplication(APP_ID,APP_SECRET);
    	$helper = new FHelper(REDIRECT_URL);
    	$sess = $helper->getSessionFromRedirect();
    	//check if facebook session exists
    	
    	if(isset($sess))
    	{
    		//$access_token = $sess->getToken();
    	
    		//1. Get facebook data
    		$request = new FacebookRequest($sess,'GET','/me');
    		$response = $request->execute();
    		$graph = $response->getGraphObject(GraphUser::classname());
    		
    		$data = array(
	    				'fname' => $graph->getFirstName(),
	    				"lname" => $graph->getLastName(),
					   	"email" => $graph->getProperty('email'),
					   	'last_login' => CURR_DATE,
					   	//'profile_pic' => 'profile_pic_'.$graph->getId(),
				 		"activated" => true,
				    	"activation_key" => $this->generateToken()
			    	);
   
    		//2. Check if email is registered
    		$info = UserAccountTb::findFirst(array(
    							"conditions"=>"email = ?0",
    							"bind" => array(0=>$data['email'])
    							));	
    		// if not registered register the user 

    		if($info == false)
    		{
    			
    			$info = new UserAccountTb();
    	
    			if($info->save($data) == false)
    			{
    				echo "Error loading please try again later";
    				die;
    				exit();
    			}
    			$prof_pic = 'https://graph.facebook.com/'.$graph->getId().'/picture?width='.PROF_WIDTH.'&height='.PROF_HEIGHT;
    			$up = $this->upload('profile_pic_'.$info->id,$prof_pic,PROF_HEIGHT,PROF_WIDTH);
    			$info->profile_pic = $up.'/profile_pic_'.$info->id.'.jpg';
    			$info->save();
    			
    			// redirect to profile
    			$this->registerSession($info->id,$info->fname,$info->lname,$info->profile_pic);
    			header('Location:'.BASE_URI.'registration/step_1');
    			echo "Redirecting...";
    		}
    		else
    		{
    			$info->last_login = CURR_DATE;
    			$info->activated = true;
    			if($info->save() == false)
    			{
    				echo "Error loading please try again later";
    				die;
    				exit();
    			}
    			$this->registerSession($info->id,$info->fname,$info->lname,$info->profile_pic);
    			//if already registered redirect to url
    			if($info->password == null)
    			{
    				header('Location:'.BASE_URI.'registration/step_1');
    			}
    			else
    			{
    				header('Location:'.BASE_URI.'feeds');
    				echo "Redirecting...";
    			}
    			
    		}
    		 
    	}
    	else
    	{
    		header('Location:'.$helper->getLoginUrl(array('scope' => 'email')));
    	}
    	die;
    }

    public function loginAction()
    {
    	$result = array();
    	if($this->request->isPost())
    	{
    		$data = $this->request->getPost('user_data');
    		$params = array();
    		parse_str($data,$params);
    		
    		$info = UserAccountTb::findFirst(array(
    					"conditions" => "email = ?0 and password = ?1",
    					"bind" => array(0=>htmlentities($params['email']),1=>md5($params['password']))
    					));

    		if($info == false)
    		{
    			$result['status'] = false;
    			$result['messages'] = "Invalid username or password";
    			$result['data'] = md5($params['password']);
    			$result['email'] =htmlentities($params['email']);
    		}
    		else
    		{
    			if($info->activated == 1)
    			{
    				$this->registerSession($info->id,$info->fname,$info->lname,$info->profile_pic);
    				$this->session->set('user_id',$info->id);
    				$info->last_login = CURR_DATE;
    				$info->save();
    				$result['status'] = true;
    				$result['link'] = BASE_URI.'feeds';			
    			}
    			else
    			{	
    				$result['status'] = "inactive";
    				$result['link'] = BASE_URI.'registration/confirm?ea='.$info->email;
    			}
    		}
    		
    		echo json_encode($result);
    		$this->view->disable();

    	}

    	
    }

    public function registerAction()
    {

    	$result = array(); // this will be the result
    	
    	if($this->request->isPost())
    	{
	    	// get post data
	    	$data = $this->request->getPost('user_data');
	    	
	    	// convert serialized data to array
	    	$params = array();
	    	parse_str($data,$params);
	    	
	    	// initialize data here

	    	$data = array(
	    				'fname' => trim($params['firstname']),
	    				"lname" => trim($params['lastname']),
					   	"email" => $params['email'],
				    	//"password" => md5(trim($params['password'])),
				    	//"confirm" => md5(trim($params['confirm'])),
				    	"activated" => false,
				    	"activation_key" => $this->generateToken()
			    	);

	    	

	    	//validation starts here
	    	$validation = new RegistrationValidation();
	    	$messages = $validation->validate($data);
			if (count($messages))
			{
				$messages2 = '';
			    foreach ($messages as $message)
			    {
			        $messages2.=$message.'<br>';
			    }
			    $result['status'] = false;
			    $result['messages'] = $messages2;
			    echo json_encode($result);   
	    		$this->view->disable();
	    		exit();
			}
	    	
		   	$info = new UserAccountTb();
		   	
		   	if($info->save($data) == false)
		   	{
		   		$result['status'] = false; 
		   		$messages = '';
		   		foreach ($info->getMessages() as $value)
		   		{
		   			$messages.=$value."<br>";
		   		}
		   		$result['messages']  = $messages;   	
		   	}
		   	else
		   	{
		   		// this return true if email success if false return the message
		   		$email = $this->sendRegistrationEmail($params["email"],$data['activation_key']); 
	    		if( $email == true)
	    		{
	    			//$this->registerSession($info->id,$info->fname,$info->lname,$info->profile_pic);
	    			$result['status'] = true;
	    			$result['messages']  = "Redirecting..";
	    		
	    		}
	    		else
	    		{
	    			$result['status'] = false;
	    			$result['messages']  = $email;
		   	
	    		}
		   	}
			echo json_encode($result);   
	    	$this->view->disable();
    	}

    }


    public function sendRegistrationEmail($to,$token)
    {
    	ini_set("SMTP","ssl://smtp.gmail.com"); 
		ini_set("smtp_port","465"); //No further need to edit your configuration files.
		$mail = new PHPMailer();
		//$mail->SMTPDebug = 1;
		$mail->SMTPAuth = true;
		$mail->Host = "smtp.gmail.com"; // SMTP server
		$mail->SMTPSecure = "ssl";
		$mail->Username = BH_EMAIL; //account with which you want to send mail. Or use this account. i dont care :-P
		$mail->Password = BH_PASSWORD; //this account's password.
		$mail->Port = "465";
		$mail->IsSMTP();  // telling the class to use SMTP
		$mail->isHTML(true);
		$rec1="trials.php@gmail.com"; //receiver. email addresses to which u want to send the mail.
		$rec2=$to;
		$mail->AddAddress($rec2);
		$mail->Subject  = "Just one more step to get started on Behomebased.ph";
		$mail->Body     = UsersController::processBody($rec2,$token);
		$mail->setFrom(BH_EMAIL,"Behomebased.ph");

		$mail->WordWrap = 200;
		if(!$mail->Send())
		{
		  return $mail->ErrorInfo;
		}
		else
		{
	 	  return true;
		}
    }

    public function processBody($email,$token)
    {
    	$message = "<div style='font-family: Tahoma, Arial, Sans-serif; font-size:12px'>".
             	    "Hi $email, <br/><br/>".
                    "You have signed up Behomebased account using the email address: $email<br/><br/>".
                    "Please confirm that this email is valid and finish creating your Behomebased account<br/><br/>".
                    "<a href='".BASE_URI."registration/confirm?ec=$email&ea=$token' target='_blank'>CONFIRM THIS EMAIL</a><br/><br/><hr/>".
                    "This notification message is confidential, may be legally privileged and is intended for the exclusive use of the addressee. If you received this message in error or are not the intended recipient, you should destroy the email message and any attachments or copies, and you are prohibited from retaining, distributing, disclosing or using any information contained. Please inform us of the delivery error by return notification. Thank you for your cooperation.</div>";
    	return $message;
    }
}



